package com.banciyuan.bcywebview.biz.search;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleSmoothActivity;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleTagSmoothActivity;
import com.banciyuan.bcywebview.biz.detail.goods.GoodsDetailActivity;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.util.CommonUtils;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.currency.CurrencyUtil;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import java.util.List;

import de.greenrobot.daoexample.model.AcgItem;
import de.greenrobot.daoexample.model.SearchContent;
import de.greenrobot.daoexample.model.TagItem;
import de.greenrobot.daoexample.model.Timeline;

/**
 * Created by squall on 2015/9/8.
 */
public class SearchContentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;
    private LayoutInflater inflater;
    private List<SearchContent> slist;
    private ImageLoader imageLoader;
    public static final int COS_TYPE = 0;
    public static final int WRITE_TYPE = 1;
    public static final int DAILY_TYPE = 2;
    public static final int GOODS_TYPE = 3;
    public static final int WORK_TYPE = 4;
    public static final int TITLE_TYPE = 5;
    public static final int USER_TYPE = 6;

    public SearchContentAdapter(List<SearchContent> slist, Context mContext) {
        imageLoader = ImageLoader.getInstance();
        this.slist = slist;
        this.mContext = mContext;
        this.inflater = LayoutInflater.from(this.mContext);
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case COS_TYPE:
                return new GridMainPicHolder(inflater.inflate(R.layout.search_grid_main_pic, parent, false));
            case WRITE_TYPE:
                return new GridWriteHolder(inflater.inflate(R.layout.search_grid_write, parent, false));
            case DAILY_TYPE:
                return new GridDailyHolder(inflater.inflate(R.layout.search_grid_daily_item, parent, false));
            case GOODS_TYPE:
                return new GridGoodsHolder(inflater.inflate(R.layout.search_grid_goods_item, parent, false));
            case WORK_TYPE:
                return new CircleViewHolder(inflater.inflate(R.layout.search_circle_item, parent, false));
            case USER_TYPE:
                return new UserViewHolder(inflater.inflate(R.layout.search_circle_item, parent, false));
            default:
            case TITLE_TYPE:
                return new TitleViewHolder(inflater.inflate(R.layout.search_result_num, parent, false));
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        switch (getItemViewType(position)) {
            case COS_TYPE:
                setMainUi((GridMainPicHolder) holder, slist.get(position).getTimeline());
                break;
            case WRITE_TYPE:
                setWriteUi((GridWriteHolder) holder, slist.get(position).getTimeline());
                break;
            case DAILY_TYPE:
                setDailyUi((GridDailyHolder) holder, slist.get(position).getTimeline());
                break;
            case GOODS_TYPE:
                setGoodsUi((GridGoodsHolder) holder, slist.get(position).getTimeline());
                break;
            case WORK_TYPE:
                setWorkUI((CircleViewHolder) holder, slist.get(position));
                break;
            case TITLE_TYPE:
                setTitleUI((TitleViewHolder) holder, slist.get(position));
                break;
            case USER_TYPE:
                setUserUI((UserViewHolder) holder, slist.get(position));
                break;
            default:
                break;
        }
    }

    private void setGoodsUi(GridGoodsHolder holder, Timeline item) {
        if (!TextUtils.isEmpty(item.getCover())) {
            holder.ivPicCover.setVisibility(View.VISIBLE);
            holder.tvItem.setVisibility(View.GONE);
            imageLoader.displayImage(item.getCover(), holder.ivPicCover, ImageOptions.options);
        }
        holder.tvGoodsPrice.setText(String.format(mContext.getString(R.string.price_format), CurrencyUtil.getMoney(item.getBasic_price())));
        OnClick onClick = new OnClick(item);
        holder.itemView.setOnClickListener(onClick);
    }

    private void setDailyUi(GridDailyHolder holder, Timeline item) {
        holder.videoIcon.setVisibility(View.GONE);
        holder.itemShadow.setVisibility(View.GONE);
        holder.ivPicCover.setVisibility(View.GONE);
        holder.tvItem.setVisibility(View.GONE);
        holder.itemLabel.setVisibility(View.GONE);
        holder.itemTitle.setVisibility(View.GONE);
        holder.itemShadow.setAlpha(0.8f);
        if (StringUtil.notNullEqual(item.getType(), "svideo")) {
            holder.ivPicCover.setVisibility(View.VISIBLE);
            holder.videoIcon.setVisibility(View.VISIBLE);
            imageLoader.displayImage(item.getCover(), holder.ivPicCover, ImageOptions.options);
        } else if (StringUtil.notNullEqual(item.getType(), "larticle")) {
            holder.ivPicCover.setVisibility(View.VISIBLE);
            holder.itemShadow.setVisibility(View.VISIBLE);
            holder.itemTitle.setVisibility(View.VISIBLE);
            holder.itemLabel.setVisibility(View.VISIBLE);
            holder.itemLabel.setText(mContext.getString(R.string.larticle));
            if (!TextUtils.isEmpty(item.getTitle())) {
                holder.itemTitle.setText(Html.fromHtml(item.getTitle()));
            }
            imageLoader.displayImage(item.getCover(), holder.ivPicCover, ImageOptions.options);
        } else {
            if (!TextUtils.isEmpty(item.getCover())) {
                holder.ivPicCover.setVisibility(View.VISIBLE);
                imageLoader.displayImage(item.getCover(), holder.ivPicCover, ImageOptions.options);
            } else {
                holder.ivPicCover.setVisibility(View.GONE);
                holder.itemShadow.setVisibility(View.VISIBLE);
                holder.tvItem.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(item.getPlain())) {
                    holder.tvItem.setText(Html.fromHtml(item.getPlain()));
                }
            }
        }
        OnClick onClick = new OnClick(item);
        holder.itemView.setOnClickListener(onClick);
    }

    private void setWriteUi(GridWriteHolder holder, Timeline item) {
        imageLoader.displayImage(item.getCover(), holder.ivPicCover, ImageOptions.options);
        holder.tvWriteTitle.setText(Html.fromHtml(item.getPlain()));
        String tagString = getTagString(item);
        if (TextUtils.isEmpty(tagString)) {
            holder.tvWriteTag.setVisibility(View.GONE);
        } else {
            holder.tvWriteTag.setVisibility(View.VISIBLE);
            holder.tvWriteTag.setText(tagString);
        }
        OnClick onClick = new OnClick(item);
        holder.itemView.setOnClickListener(onClick);
    }

    private void setMainUi(final GridMainPicHolder holder, final Timeline item) {
        imageLoader.displayImage(item.getCover(), holder.ivPicCover, ImageOptions.options);
        OnClick onClick = new OnClick(item);
        holder.itemView.setOnClickListener(onClick);
    }

    @Override
    public int getItemViewType(int position) {
        switch (TimelineFactory.whichType(slist.get(position).getTimeline())) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                return COS_TYPE;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                return WRITE_TYPE;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                return DAILY_TYPE;
            case TimelineFactory.TIMELINE_TYPE_GOODS:
                return GOODS_TYPE;
            default:
                String otype = slist.get(position).getOtype();
                if (!TextUtils.isEmpty(otype)) {
                    if (otype.equals("circles")) {
                        return WORK_TYPE;
                    } else if (otype.equals("users")) {
                        return USER_TYPE;
                    } else {
                        return TITLE_TYPE;
                    }
                } else
                    return TITLE_TYPE;
        }
    }

    @Override
    public int getItemCount() {
        return slist.size();
    }

    private class TitleViewHolder extends RecyclerView.ViewHolder {
        private TextView title;

        public TitleViewHolder(View convertView) {
            super(convertView);
            title = (TextView) convertView.findViewById(R.id.ground_zan_type_tv);
        }
    }

    private class CircleViewHolder extends RecyclerView.ViewHolder {
        LinearLayout circleContainer;

        public CircleViewHolder(View convertView) {
            super(convertView);
            circleContainer = (LinearLayout) convertView.findViewById(R.id.circle_container);
        }
    }

    private class UserViewHolder extends RecyclerView.ViewHolder {
        LinearLayout circleContainer;

        public UserViewHolder(View convertView) {
            super(convertView);
            circleContainer = (LinearLayout) convertView.findViewById(R.id.circle_container);
        }
    }


    private class GridMainPicHolder extends RecyclerView.ViewHolder {
        ImageView ivPicCover;

        public GridMainPicHolder(View itemView) {
            super(itemView);
            ivPicCover = (ImageView) itemView.findViewById(R.id.siv_item);
        }
    }

    private class GridWriteHolder extends RecyclerView.ViewHolder {
        ImageView ivPicCover;
        TextView tvWriteTitle;
        TextView tvWriteTag;

        public GridWriteHolder(View itemView) {
            super(itemView);
            ivPicCover = (ImageView) itemView.findViewById(R.id.siv_item);
            tvWriteTitle = (TextView) itemView.findViewById(R.id.tv_write_title);
            tvWriteTag = (TextView) itemView.findViewById(R.id.tv_write_tag);
        }
    }

    private class GridDailyHolder extends RecyclerView.ViewHolder {
        ImageView ivPicCover;
        TextView tvItem;
        TextView itemTitle;
        View itemShadow;
        TextView itemLabel;
        ImageView videoIcon;

        public GridDailyHolder(View itemView) {
            super(itemView);
            ivPicCover = (ImageView) itemView.findViewById(R.id.siv_item);
            tvItem = (TextView) itemView.findViewById(R.id.tv_item);
            videoIcon = (ImageView) itemView.findViewById(R.id.video_icon);
            itemShadow = itemView.findViewById(R.id.item_shadow);
            itemLabel = (TextView) itemView.findViewById(R.id.item_label);
            itemTitle = (TextView) itemView.findViewById(R.id.tv_title);
        }
    }

    private class GridGoodsHolder extends RecyclerView.ViewHolder {
        ImageView ivPicCover;
        TextView tvGoodsPrice;
        TextView tvItem;

        public GridGoodsHolder(View itemView) {
            super(itemView);
            ivPicCover = (ImageView) itemView.findViewById(R.id.siv_item);
            tvGoodsPrice = (TextView) itemView.findViewById(R.id.tv_goods_price);
            tvItem = (TextView) itemView.findViewById(R.id.tv_item);
        }
    }


    private void setTitleUI(TitleViewHolder titleViewHolder, SearchContent searchContent) {
        if (searchContent.is_show()) {
            titleViewHolder.title.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(searchContent.getTitle_num_format())) {
                titleViewHolder.title.setText(Html.fromHtml(searchContent.getTitle_num_format()));
            }
        } else {
            titleViewHolder.title.setVisibility(View.GONE);
        }
    }

    @NonNull
    private String getTagString(Timeline mItem) {
        StringBuffer sb = new StringBuffer();
        if (null != mItem && null != mItem.getPost_tags()) {
            for (String s : mItem.getPost_tags()) {
                sb.append(s + "/");
            }
            if (sb.length() > 0)
                sb.delete(sb.length() - 1, sb.length());
        }
        return sb.toString();
    }

    private void setUserUI(UserViewHolder userViewHolder, final SearchContent searchContent) {
        if (!searchContent.is_show()) {
            userViewHolder.circleContainer.setVisibility(View.GONE);
            return;
        }
        userViewHolder.circleContainer.setVisibility(View.VISIBLE);
        userViewHolder.circleContainer.removeAllViews();
        final List<SearchContent> circlelist = searchContent.getUserContents();
        int rowCount = 0;
        if (CommonUtils.getWidthPixels((Activity) mContext) > 750) {
            rowCount = 5;
        } else {
            rowCount = 4;
        }
        LinearLayout ll = new LinearLayout(mContext);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        for (int j = 0; j < rowCount; j++) {
            LinearLayout.LayoutParams llchild = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            llchild.weight = 1;
            llchild.bottomMargin = UIUtils.dip2px(16, mContext);
            LinearLayout itemView = (LinearLayout) View.inflate(mContext, R.layout.local_user_item, null);
            itemView.setGravity(Gravity.CENTER);
            itemView.setLayoutParams(llchild);
            if (j <= rowCount - 1) {
                itemView.setVisibility(View.VISIBLE);
                TextView tv = (TextView) itemView.findViewById(R.id.tv_work);
                ImageView iv = (ImageView) itemView.findViewById(R.id.iv_work);
                tv.setMaxWidth(CommonUtils.getWidthPixels((Activity) mContext) / rowCount - UIUtils.dip2px(16, mContext));
                if (j < circlelist.size() && j < rowCount - 1) {
                    final SearchContent c = circlelist.get(j);
                    tv.setText(c.getUname());
                    ImageLoader.getInstance().displayImage(c.getAvatar(), iv, ImageOptions.optionHead);
                    itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            gotoUtil.gotoAct(mContext, SmoothPersonActivity.class, c.getUid());
                        }
                    });
                } else if (rowCount > circlelist.size() && j == circlelist.size()) {
                    iv.setImageResource(R.drawable.go_all_user);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            BaseObserver.getInstance().notifyWatchers(BaseObserver.SEARCH_GOTO_USER);
                        }
                    });
                } else if (rowCount <= circlelist.size() && j == rowCount - 1) {
                    iv.setImageResource(R.drawable.go_all_user);
                    iv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            BaseObserver.getInstance().notifyWatchers(BaseObserver.SEARCH_GOTO_USER);
                        }
                    });
                }
            } else {
                itemView.setVisibility(View.INVISIBLE);
            }
            ll.addView(itemView);
        }
        userViewHolder.circleContainer.addView(ll);
    }


    private void setWorkUI(final CircleViewHolder viewCircle, final SearchContent searchContent) {
        if (!searchContent.is_show()) {
            viewCircle.circleContainer.setVisibility(View.GONE);
            return;
        }
        viewCircle.circleContainer.setVisibility(View.VISIBLE);
        viewCircle.circleContainer.removeAllViews();
        final List<SearchContent> circlelist = searchContent.getCircleContents();
        int rowCount = 0;
        if (CommonUtils.getWidthPixels((Activity) mContext) > 750) {
            rowCount = 5;
        } else {
            rowCount = 4;
        }
        int line = circlelist.size() % rowCount == 0 ? circlelist.size() / rowCount : circlelist.size() / rowCount + 1;
        line = line >= 2 ? 2 : line;
        for (int i = 0; i < line; i++) {
            LinearLayout ll = new LinearLayout(mContext);
            ll.setOrientation(LinearLayout.HORIZONTAL);
            for (int j = 0; j < rowCount; j++) {
                final int index = j + (i * rowCount);
                LinearLayout.LayoutParams llchild = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                llchild.weight = 1;
                llchild.bottomMargin = UIUtils.dip2px(16, mContext);
                LinearLayout itemView = (LinearLayout) View.inflate(mContext, R.layout.local_circle_item, null);
                itemView.setGravity(Gravity.CENTER);
                itemView.setLayoutParams(llchild);
                if (index < circlelist.size()) {
                    itemView.setVisibility(View.VISIBLE);
                    final SearchContent circle = circlelist.get(index);
                    final AcgItem c = circle.getAcgItem();
                    final TagItem t = circle.getTagItem();
                    TextView tv = (TextView) itemView.findViewById(R.id.tv_work);
                    ImageView iv = (ImageView) itemView.findViewById(R.id.iv_work);
                    tv.setMaxWidth(CommonUtils.getWidthPixels((Activity) mContext) / rowCount - UIUtils.dip2px(16, mContext));
                    if ("work".equals(circle.getOtype())) {
                        tv.setText(c.getReal_name());
                        ImageLoader.getInstance().displayImage(c.getImg_src(), iv, ImageOptions.options);
                        itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(mContext, CircleSmoothActivity.class);
                                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, c.getId());
                                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, c.getReal_name());
                                intent.putExtra("from", 0);
                                mContext.startActivity(intent);
                            }
                        });
                    } else {
                        tv.setText(t.getName());
                        ImageLoader.getInstance().displayImage(t.getCover(), iv, ImageOptions.options);
                        itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(mContext, CircleTagSmoothActivity.class);
                                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, t.getName());
                                intent.putExtra("type", "tag");
                                mContext.startActivity(intent);
                            }
                        });
                    }
                } else {
                    itemView.setVisibility(View.INVISIBLE);
                }
                ll.addView(itemView);
            }
            viewCircle.circleContainer.addView(ll);
        }
    }

    class OnClick implements View.OnClickListener {
        private Timeline mItem;

        public OnClick(Timeline mItem) {
            this.mItem = mItem;
        }

        @Override
        public void onClick(View v) {
            int whichType = TimelineFactory.whichType(mItem.getOtype_data(), mItem.getOtype());
            switch (whichType) {
                case TimelineFactory.TIMELINE_TYPE_COSER:
                    DetailDataHelper.gotoCosDetail(mContext, mItem.getRp_id(), mItem.getCp_id(), false);
                    break;
                case TimelineFactory.TIMELINE_TYPE_ILLUST:
                    DetailDataHelper.gotoDrawerDetail(mContext, mItem.getRp_id(), mItem.getDp_id(), false);
                    break;
                case TimelineFactory.TIMELINE_TYPE_DAILY:
                    DetailDataHelper.gotoDailyDetail(mContext, mItem.getUd_id(), false);
                    break;
                case TimelineFactory.TIMELINE_TYPE_WRITER:
                    DetailDataHelper.gotoWriterDetail(mContext, mItem.getRp_id(), mItem.getWp_id(), false);
                    break;
                case TimelineFactory.TIMELINE_TYPE_GOODS:
                    gotoUtil.gotoAct(mContext, GoodsDetailActivity.class, mItem.getZg_id());
                    break;
            }
        }
    }
}
